import axios from 'axios'
class Global {
    constructor(Vue, store) {
        this.INDEX_PATH = '/';
        this.$vue = Vue;
        this.store = store;
    }
    async build() {
        this.user = await this.loginData();
        this.location = await this.getDetailLocation();
        return Promise.resolve();
    }
    init(vm) {
        this.$root = vm
    }
    loginData() {
        //获取用户登录信息
        return new Promise((resolve) => {
            axios
                .get("https://elm.cangdu.org/v1/user")
                .then(res => {
                    if (res.status == 200) {
                        this.store.commit("RECEIVE_USER_INFO", res.data);
                        this.store.commit("RECEIVE_USER_ID", res.data.user_id);
                        this.store.commit("RECEIVE_USER_ISLOGIN", res.data.is_active);
                        resolve(res)
                    }
                })
                .catch(error => {
                    resolve(error)
                });
        })
    }
    getLocation() {
         //获取粗略的用户经纬度
        return new Promise((resolve) => {
            axios
                .get("https://elm.cangdu.org/v1/cities?type=guess")
                .then(res => {
                    resolve(res)
                })
                .catch(error => {
                    resolve(res)
                });
        })
    }
    async getDetailLocation() {
        //获取详细的地理位置信息
        const res = await this.getLocation();
        return new Promise((resolve) => {
            if (res.data) {
                let location = res.data.latitude + "," + res.data.longitude;
                axios
                    .get("https://elm.cangdu.org/v2/pois/" + location)
                    .then(res => {
                        this.store.commit("RECEIVE_CITISE_LOCATION", res.data);
                        resolve(res.data)
                    })
                    .catch(error => {
                        resolve(error)
                    });
            }
        })
    }

}
export default Global;